﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;

using ProjectBase.Core;
using ProjectBase.Core.Service;
using ProjectBase.Mvc;

using $safeprojectname$.Business.Services;
using $prjsn$.Entity.Services;

namespace $safeprojectname$.Providers
{
    public class ProjectRoleProvider : WindowsTokenRoleProvider
    {
        #region members

        private const string Viewer = "Viewer";
        private IUserFacade _userFacade;

        #endregion members

        public virtual User User
        {
            get { return SecurityManager.User; }
        }

        public virtual void ChangeCurrentRole(string role)
        {
            if (SecurityManager.GetRolesForUser().Contains(role))
            {
                var user = User;
                user.CurrentRole = role;
                UserFacade.Update(user);
            }
        }

        public override string[] GetRolesForUser(string username)
        {
            if (!Identity.IsAuthenticated)
            {
                return new[] { Viewer };
            }

            var user = UserFacade.GetByLogin(username);

            if (user.Is())
            {
                return user.Roles.ToArray();
            }
            return new string[0];
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            return GetRolesForUser(username).Any(r => r.Equals(roleName, StringComparison.Ordinal));
        }

        #region NotImplemented

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException(GetType().FullName + " does not support this operation");
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException(GetType().FullName + " does not support this operation");
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException(GetType().FullName + " does not support this operation");
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException(GetType().FullName + " does not support this operation");
        }

        #endregion NotImplemented

        #region properties

        protected virtual IIdentity Identity
        {
            get { return Thread.CurrentPrincipal.Identity; }
        }

        public IUserFacade UserFacade
        {
            protected get { return _userFacade ?? (_userFacade = Factory.CreateInstance<IUserFacade>()); }
            set { _userFacade = value; }
        }

        #endregion properties
    }
}